#!/usr/bin/env python3
"""
启动脚本：同时启动FastAPI后端服务和Gradio管理界面

使用方法：
python start_admin.py

这将启动：
- FastAPI服务器在 http://127.0.0.1:8000
- Gradio管理界面在 http://127.0.0.1:7860
"""

import subprocess
import time
import sys
import threading
import signal
import os
import socket
import json


def get_local_ip():
    """获取本机IP地址"""
    try:
        # 创建一个UDP socket连接到外部地址来获取本机IP
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            # 连接到Google DNS，不会实际发送数据
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            return local_ip
    except Exception:
        # 如果获取失败，返回localhost
        return "127.0.0.1"


def create_config_file(api_base_url):
    """创建配置文件供Gradio使用"""
    config = {
        "api_base_url": api_base_url
    }
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
    with open(config_path, 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=2)
    return config_path


def start_fastapi():
    """启动FastAPI服务器"""
    print("启动FastAPI服务器...")
    return subprocess.Popen([
        sys.executable, "-m", "uvicorn", "main:app",
        "--reload", "--host", "0.0.0.0", "--port", "8080"
    ], cwd=os.path.dirname(os.path.abspath(__file__)))


def start_gradio():
    """启动Gradio管理界面"""
    print("等待FastAPI服务器启动...")
    time.sleep(3)  # 等待FastAPI启动
    print("启动Gradio管理界面...")
    return subprocess.Popen([
        sys.executable, "-c", 
        "from ui.admin_ui import launch_admin_ui; launch_admin_ui()"
    ], cwd=os.path.dirname(os.path.abspath(__file__)))


def main():
    """主函数"""
    print("=== 飞书公式抄写小程序 - 管理控制台 ===")
    print("正在启动服务...")

    # 获取本机IP地址
    local_ip = get_local_ip()
    api_base_url = f"http://{local_ip}:8080/api/v1"

    print(f"检测到本机IP: {local_ip}")
    print(f"API基础URL: {api_base_url}")

    # 创建配置文件
    config_path = create_config_file(api_base_url)
    print(f"配置文件已创建: {config_path}")

    # 启动FastAPI服务器
    fastapi_process = start_fastapi()

    # 启动Gradio界面
    gradio_process = start_gradio()

    print("\n服务启动完成！")
    print(f"- FastAPI API文档: http://{local_ip}:8080/docs")
    print(f"- Gradio管理界面: http://{local_ip}:7860")
    print(f"- 本地访问: http://127.0.0.1:7860")
    print(f"- 真机访问: http://{local_ip}:7860")
    print("\n按 Ctrl+C 停止所有服务")
    
    def signal_handler(sig, frame):
        print("\n正在停止服务...")
        fastapi_process.terminate()
        gradio_process.terminate()
        print("服务已停止")
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    
    try:
        # 等待进程结束
        fastapi_process.wait()
        gradio_process.wait()
    except KeyboardInterrupt:
        signal_handler(None, None)


if __name__ == "__main__":
    main()
